<?php
/**
 *
 * User: wesley
 * Date: 2017/11/9 0009
 * Time: 14:31
 * Email: wu93wesley@foxmail.com
 */

namespace app\api\controller;

use phpmailer\phpmailer;
use submail\messagexsend;

class Code extends Common {
    public function get_code () {
        $username = $this->params[ 'username' ];//参数用户名
        $exist = $this->params[ 'is_exist' ];//参数是否存在  1：存在  0：不存在
        $username_type = $this->check_username($username);//检测并返回用户名类型
        switch ($username_type) {
            case 'phone':
                $this->get_code_by_username($username, 'phone', $exist);
                break;
            case 'email':
                $this->get_code_by_username($username, 'email', $exist);
                break;
        }
    }

    public function get_code_by_username ($username, $type, $exist) {
        if ($type == 'phone') {
            $type_name = '手机';
        } else {
            $type_name = '邮箱';
        }
        /**检测邮箱或手机号是否存在*/
        $this->check_exist($username, $type, $exist);
        /**检测验证码请求频率，30秒一次*/
        if (session("?" . $username . '_last_send_time')) {
            if (time() - session($username . '_last_send_time') < 30) {
                $this->message(400, $type_name . '验证码，每30秒只能发送一次！');
            }
        }
        /** 生成验证码*/
        $code = $this->create_code(6);
        /**使用session存储验证码，方便比对， MD5加密*/
        session($username . '_code', $code);
        /**使用session存储验证码的发送时间*/
        session($username . '_last_send_time', time());
        /**发送验证码*/
        if ($type == 'phone') {
            $this->send_code_to_phone($username, $code);
        } else {
            $this->send_code_to_email($username, $code);
        }
    }

    /**
     * 生成验证码
     * @param $num [int] 【验证码位数】
     * @return int              【生成的验证码】
     */
    public function create_code ($num) {
        $max = pow(10, $num) - 1;
        $min = pow(10, $num - 1);
        return rand($min, $max);
    }

    public function send_code_to_phone ($phone, $code) {
        $submail = new MESSAGEXsend();

    }

    public function send_code_to_email ($email, $code) {
//        echo '发送到邮箱';

        $toemail = $email;
        $mail = new PHPMailer();
        $mail->isSMTP();
        $mail->SMTPAuth = true;
        $mail->SMTPDebug = 1;
        $mail->CharSet = 'utf8';
        $mail->Host = 'smtp.qq.com';

        $mail->Username = '1124700977@qq.com';
        $mail->Password = 'ajjpecfpsjsmhhjf';
        $mail->SMTPSecure = 'ssl';

        $mail->Port = 465;
        $mail->setFrom('1124700977@qq.com', '接口测试');
        $mail->addAddress($toemail, 'test');
        $mail->addReplyTo('1124700977@qq.com', 'Reply');
        $mail->Subject = '您有新的验证码 请注意查收！';
        $mail->Body = "这是一个测试邮件,您的验证码为$code,验证码的有效期为1分钟，本邮件请勿回复!";
        if (!$mail->send()) {
            $this->message(400, $mail->ErrorInfo);
//            return $mail->ErrorInfo;
        } else {
            $this->message(200, '验证码已经发送成功，请注意查收！');
        }
    }
}